/*
 * Copyright (c) 2020 WildFireChat. All rights reserved.
 */

package com.cloudptt.wp.ui;


import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.cloudptt.api.comm.CauseCont;
import com.cloudptt.api.comm.CommDlg;
import com.cloudptt.api.comm.Common;
import com.cloudptt.api.product.Product;
import com.cloudptt.api.product.ProductConst;
import com.cloudptt.api.product.func.sys.SysStateInfo;
import com.cloudptt.api.product.func.sys.listener.SysListener;
import com.cloudptt.api.product.log.Log;
import com.cloudptt.wp.R;
import com.cloudptt.wp.ScreenManager;
import com.cloudptt.wp.SysApplication;

import java.util.ArrayList;
import java.util.List;


public class SplashActivity extends AppCompatActivity implements SysListener {

    protected static final int GPS_REQUEST_CODE = 1;
    private final static int OVERLAY_REQUEST_CODE = 10;
    private final static int WRITE_SETTINGS_REQUEST_CODE = 11;
    private final static int REQUEST_INSTALL_CODE = 20;
    public final static String KEY_HOME = "MainActivity";
    public final static String KEY_NAME_ISFIRST = "isFirstLogin";
    private Product product;
    private SharedPreferences mSharedPreferences;
    private LocationManager mLocationManager;

    private static final int PERMISSION_REQUEST_STORAGE = 1;
    private List<String> mPermissionList = new ArrayList<String>();
    private String[] mPermissions = new String[] {
            Manifest.permission.CHANGE_NETWORK_STATE,
            Manifest.permission.CALL_PHONE,
            Manifest.permission.INTERNET,
            Manifest.permission.MODIFY_AUDIO_SETTINGS,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.WRITE_CONTACTS,
            Manifest.permission.WAKE_LOCK,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.USE_SIP,
            Manifest.permission.CAMERA,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA
    };

    private final ContentObserver mGpsMonitor = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange) {
            // TODO Auto-generated method stub
            super.onChange(selfChange);

            if(mLocationManager != null){
                boolean enable = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

                Log.debug(this.getClass(), "onChange GPS state");
                if(enable){
                    if(product != null){
                        product.startServer(ProductConst.Func_Local);
                    }

                }else{
                    if(product != null){
                        product.stopServer(ProductConst.Func_Local);
                    }
                }
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        Log.debug(this.getClass(), "onCreate " + Common.getDateAndTime());
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//        window.setStatusBarColor(Color.parseColor("#162F4A"));
        window.setStatusBarColor(getResources().getColor(R.color.gradient_start));

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(SysApplication.GROUP_CREATE_RESULT_ACTION);
        mResultReceiver = new SplashActivity.ResultReceiver();
        registerReceiver(mResultReceiver, intentFilter);
        ScreenManager.getScreenManager().pushActivity(SplashActivity.this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.debug(this.getClass(), "onResume 1 product = " + product);
        if(product == null){
            SysApplication app = ((SysApplication) getApplicationContext());
            Log.debug(this.getClass(), "onResume app = " + app);
            this.product = app.getProduct();
        }
        Log.debug(this.getClass(), "onResume 2 product = " + product);
        if(product != null)
        {
            goProcess();
            product.setSysListener(this.getClass().getName(),this);
        }
        else
        {
            new Handler().postDelayed(this::checkPermission, 500);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(product == null)
        {
            SysApplication app = ((SysApplication) getApplicationContext());
            this.product = app.getProduct();
        }
        if(product != null)
        {
            product.setSysListener(this.getClass().getName(),null);
        }
    }

    private boolean checkInstallPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return getPackageManager().canRequestPackageInstalls();
        }
        return true; // 8.0 以下默认允许
    }

    private void requestInstallPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)
                    .setData(Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, REQUEST_INSTALL_CODE);
        }
    }

    private void checkPermission() {
        Log.debug(this.getClass(), "checkPermission Build.VERSION = " + Build.VERSION.SDK_INT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            mPermissionList.clear();
            for (String permission : mPermissions)
            {
                if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED)
                {
                    mPermissionList.add(permission);
                }
            }

            boolean canDrawOverlays = Settings.canDrawOverlays(getApplicationContext());
            boolean canRequestPackageInstalls = checkInstallPermission();
            Log.debug(this.getClass(), "mPermissionList = " + mPermissionList + " canDrawOverlays = " + canDrawOverlays + " canRequestPackageInstalls = " + canRequestPackageInstalls);
            if (!mPermissionList.isEmpty())
            {
                Log.debug(this.getClass(), "checkPermission 1" );
                String[] reqpermissions = mPermissionList.toArray(new String[mPermissionList.size()]);
                requestPermissions(reqpermissions, PERMISSION_REQUEST_STORAGE);

            } else if(!canDrawOverlays)
            {
                Log.debug(this.getClass(), "checkPermission canDrawOverlays" );
                startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:"+getPackageName())), OVERLAY_REQUEST_CODE);
            }
            else if(!canRequestPackageInstalls)
            {
                Log.debug(this.getClass(), "checkPermission canRequestPackageInstalls" );
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, REQUEST_INSTALL_CODE);
            }
            else
            {
			    Log.debug(this.getClass(), "checkPermission 3" );
                ((SysApplication) getApplication()).creatProduct(this);
            }
            Log.debug(this.getClass(), "checkPermission 4" );
        }
        else
        {
            Log.debug(this.getClass(), "checkPermission 5" );
            ((SysApplication) getApplication()).creatProduct(this);
        }
        Log.debug(this.getClass(), "checkPermission end" );
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        Log.debug(this.getClass(), "onRequestPermissionsResult requestCode = " + requestCode);
        boolean grant = true;
        if (requestCode == PERMISSION_REQUEST_STORAGE) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    grant = false;
                    boolean showRequestPermission = shouldShowRequestPermissionRationale(permissions[i]);
                    if (showRequestPermission) {
                        Intent intent = new Intent();
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                        intent.setData(Uri.fromParts("package", getPackageName(), null));
                        startActivity(intent);
                        finish();
                    }
                }
            }
            boolean canDrawOverlays = Settings.canDrawOverlays(getApplicationContext());
            Log.debug(this.getClass(), "onRequestPermissionsResult canDrawOverlays = " + canDrawOverlays);
            if(!canDrawOverlays){
                grant = false;
                Log.debug(this.getClass(), "checkPermission 2" );
                startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:"+getPackageName())), OVERLAY_REQUEST_CODE);
            }

            boolean canInstall = Settings.canDrawOverlays(getApplicationContext());
            Log.debug(this.getClass(), "onRequestPermissionsResult canInstall = " + canInstall);
//            if (requestCode == REQUEST_INSTALL_CODE) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
                        && !canInstall) {
                    // 权限已授予，执行安装操作
                    grant = false;
                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                    intent.setData(Uri.parse("package:" + getPackageName()));
                    startActivityForResult(intent, REQUEST_INSTALL_CODE);
                }
//            }

            Log.debug(this.getClass(), "onRequestPermissionsResult grant = " + grant);
            if (grant) {
                ((SysApplication) getApplication()).creatProduct(this);
            }
        }
        else
        {
            checkPermission();
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private SplashActivity.ResultReceiver mResultReceiver;

    @Override
    public void onSysState(SysStateInfo stateInfo) {
        Log.debug(this.getClass(), "onSysState stateInfo = " + stateInfo);
        int state = stateInfo.getState();
        int cause = stateInfo.getCause();

        if(SysStateInfo.SysState_SvrStartState == state)
        {
            if(cause != SysStateInfo.Cause_Suc)
            {
                String errStr = CauseCont.getAuthErrStr(cause, SplashActivity.this);
                CommDlg.showToast(SplashActivity.this, errStr);
                showLogin();
            }
        }
        else if(SysStateInfo.SysState_SipPulishSucState == state)
        {
            showMain();
        }
    }

    @Override
    public void onErrer(String str) {

    }

    @Override
    public void onForceDetach() {

    }

    @Override
    public void onKeepAlive(boolean isconnected) {

    }

    @Override
    public void onSvrRestart() {

    }


    public class ResultReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (SysApplication.GROUP_CREATE_RESULT_ACTION.equals(action)) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        goProcess();
                    }
                });
            }
        }
    }

    private void goProcess() {
        if(product == null)
        {
            SysApplication app = ((SysApplication) getApplicationContext());
            this.product = app.getProduct();
        }

        if(product != null){
//            SysApplication app = ((SysApplication) getApplicationContext());
//            Product product = app.getProduct();
//            {
//                product.checkCurVersion(SplashActivity.this,false,false,null);
//            }

            SysStateInfo sysInfo = product.getSysStateInfo();
            Log.debug(this.getClass(), "goProcess sysInfo = "+sysInfo);
            if(sysInfo != null) {
                goToSomeActivityByInfo(sysInfo);
            }

            getContentResolver().registerContentObserver(Settings.Secure.getUriFor(Settings.System.LOCATION_PROVIDERS_ALLOWED), false, mGpsMonitor);
        }
    }

    private boolean checkGpsEnable(){
        if(mLocationManager != null){
            return mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        }
        return false;
    }

    private void openGpsSettings(){

        new Throwable().printStackTrace();

        boolean isGPSenable = checkGpsEnable();
        Log.debug(this.getClass(), "isGPSenable = "+isGPSenable);
		/*if(isGPSenable){
			if(product != null){
				product.startServer(ProductConst.Func_Local);
			}
		}else{*/

        if(mSharedPreferences.getBoolean(KEY_NAME_ISFIRST, false)){
            return;
        }

        DialogInterface.OnClickListener okListener = new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, GPS_REQUEST_CODE);
                return;
            }
        };

        DialogInterface.OnClickListener cancelListener = new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                CommDlg.showToast(SplashActivity.this, R.string.cannot_use_location);
                return;
            }
        };


        CommDlg.showNormalDlg(this, null, getResources().getString(R.string.please_open_gps), okListener, cancelListener);

        mSharedPreferences.edit().putBoolean("isFirstLogin", true).commit();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        Log.debug(this.getClass(), "onActivityResult resultCode = " + resultCode);
        if(GPS_REQUEST_CODE == requestCode){
            Log.debug(this.getClass(), "onActivityResult");
            if(!checkGpsEnable()){
                CommDlg.showToast(SplashActivity.this, R.string.cannot_use_location);
            }else{
                if(product != null){
                    product.startServer(ProductConst.Func_Local);
                }
                //openGpsSettings();
            }
        }else if(OVERLAY_REQUEST_CODE == requestCode)
        {
            Log.debug(this.getClass(), "overlay result = "+resultCode);
            ((SysApplication) getApplication()).creatProduct(this);
        }
        else if(WRITE_SETTINGS_REQUEST_CODE == requestCode)
        {
            Log.debug(this.getClass(), "write settings result = "+resultCode);
        }
        else
        {
            checkPermission();
        }
    }

    private void goToSomeActivityByInfo(SysStateInfo sysStateInfo){
        Log.debug(this.getClass(), "goToSomeActivityByInfo sysStateInfo = " + sysStateInfo);
        if(sysStateInfo != null){
            int state = sysStateInfo.getState();
            int cause = sysStateInfo.getCause();
            if(SysStateInfo.SysState_SvrStartState == state
                    && SysStateInfo.Cause_Suc != cause)
            {
                showLogin();
            }
            else if(SysStateInfo.SysState_SipPulishSucState == state
                    && SysStateInfo.Cause_Suc == cause)
            {
                showMain();
            }

        }
    }

    private void showMain() {
//        Intent intent = new Intent(this, MainActivity.class);
//        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//        Bundle bundle = ActivityOptionsCompat.makeCustomAnimation(SplashActivity.this,
//                android.R.anim.fade_in, android.R.anim.fade_out).toBundle();
//        startActivity(intent, bundle);
        Intent intent = new Intent();
        intent.setClass(SplashActivity.this, MainActivity.class);
        //		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        ScreenManager.getScreenManager().popAllActivity();
        startActivity(intent);
    }

    private void showLogin() {
//        Intent intent;
//        intent = new Intent(this, Login.class);
//        intent.putExtra("isKickedOff", getIntent().getBooleanExtra("isKickedOff", false));
//        Bundle bundle = ActivityOptionsCompat.makeCustomAnimation(SplashActivity.this,
//                android.R.anim.fade_in, android.R.anim.fade_out).toBundle();
//        startActivity(intent, bundle);
        Intent intent = new Intent();
        intent.setClass(SplashActivity.this, Login.class);
        //		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        ScreenManager.getScreenManager().popAllActivity();
        startActivity(intent);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mResultReceiver);
    }
}
